#coding=utf-8
#Created on 2011-06-14
#@author: glen

import datetime
from django import template
register = template.Library()

from django.conf import settings

@register.filter
def time_beauty(value):
    '''
    将value转换为更友好的时间显示格式
    value: datetime
    '''

    # django 1.4之后需要使用utc时间
    #now_time = datetime.datetime.utcnow().replace(tzinfo=utc)
    now_time = datetime.datetime.now()
    delta_time = now_time - value
    delta_date = now_time.date() - value.date()
    if delta_time.seconds < 60 and delta_time.days < 1:
        return u'刚刚'
    elif delta_time.seconds < 60*60 and delta_time.days < 1:
        return u'%i分钟前' %(delta_time.seconds/60)
    elif delta_date.days < 1:
        return value.strftime('今天 %H:%M')
    elif delta_date.days < 2:
        return value.strftime('昨天 %H:%M')
    elif now_time.year == value.year:
        return value.strftime('%m月%d日 %H:%M')
    else:
        return value.strftime('%Y年%m月%d日')

@register.filter
def truncatechars(value, arg):
    if value is None:
        return value
    elif type(arg) != int:
        return value
    elif len(value) > arg:
        return "%s..." % value[:arg]
    else:
        return value

class StaticNode(template.Node):
    def __init__(self, path):
        self.path = path.replace("\"", "").replace("\'", "")
    def render(self, context):
        return '%s%s' %(settings.STATIC_URL, self.path)
